<template>
  <div class="search-check">
    <div
      v-for="item in options"
      :key="item.label"
      :title="item.label"
      :class="{ active: active === item.value }"
      class="check-option"
      @mousedown.stop="handleClick(item.value)"
      @mouseover="active = item.value">
      <span class="check-label">{{ item.label }}</span>
      <img
        v-if="check.includes(item.value)"
        class="check-icon"
        :src="CheckSvg"
        alt="" />
    </div>
    <div class="search-popover-footer">
      <a-button size="small" @click="handleCancel">取消</a-button>
      <a-button
        type="primary"
        size="small"
        :disabled="!check.length"
        @click="handleOk">
        确认
      </a-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, ref, watchEffect } from 'vue'

import type { LabelValue } from '../../../types'
import { useActiveKeyDown } from '../hooks/useActiveKeyDown'
import CheckSvg from '../icons/check.svg'
const props = defineProps<{
  options: LabelValue[]
}>()

const emit = defineEmits<{
  ok: [value: LabelValue[]]
  cancel: []
}>()

type Value = LabelValue['value']

const actives = computed(() => props.options.map((v) => v.value))

const active = ref<Value>(actives.value[0])

const check = ref<Value[]>([])

const checks = computed(() =>
  props.options.filter((v) => check.value.includes(v.value))
)

watchEffect(() => {
  onClear()
})

function handleClick(val: Value) {
  const idx = check.value.findIndex((v) => v === val)
  idx > -1 ? check.value.splice(idx, 1) : check.value.push(val)
}

function handleOk() {
  emit('ok', checks.value)
  onClear()
}

function handleCancel() {
  emit('cancel')
  onClear()
}

function onClear() {
  active.value = actives.value[0]
  check.value = []
}

useActiveKeyDown({
  active,
  options: actives,
  enterFn: () => {
    if (!props.options.length || !active.value) return
    handleClick(active.value)
  }
})
</script>
